﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wicture.QPZS.EPC.API.Domain.Entities;
using Wicture.QPZS.EPC.API.Throttlings;

namespace Wicture.QPZS.EPC.API.Throtteds
{
    public class ThrottedProxy : IThrottedProxy
    {
        private readonly IThrottled[] _throttleds;

        public ThrottedProxy(IThrottled[] throttleds)
        {
            _throttleds = throttleds;
        }

        public void Throtted(ThrottlingContext invokeContext)
        {
            var throttleds = SelectThrottleds(invokeContext);
            if (!(throttleds?.Any() ?? false))
            {
                return;
            }
            foreach (var throttled in throttleds)
            {
                throttled.Invoke(invokeContext);
            }
        }

        private IEnumerable<IThrottled> SelectThrottleds(ThrottlingContext invokeContext)
        {
            return _throttleds.Where(s => s.ServicePackageTypes.Contains(invokeContext.ServicePackage.PackageType)).OrderBy(s => s.Order);
        }
    }
}
